<template>
	<div class="system-authorizeAdd-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px" draggable>
			<el-form ref="authorizeAddDialogFormRef" :model="state.ruleForm" size="default" label-width="90px" :rules="rules">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色" prop="roleId">
							<el-select v-model="state.ruleForm.roleId" placeholder="请选择角色" clearable class="w100" @change="roleChange()">
								<el-option label="运营管理人员" value="0"></el-option>
                <el-option label="学生" value="1"></el-option>
								<el-option label="普通教师" value="2"></el-option>
								<el-option label="家长" value="5"></el-option>
								<el-option label="教师管理员" value="3"></el-option>
								<el-option label="学校管理员" value="7"></el-option>
								<el-option label="教育局管理员" value="6"></el-option>
								<el-option label="教育局领导" value="8"></el-option>
								<el-option label="部门负责人" value="9"></el-option>
								<el-option label="部门工作人员" value="10"></el-option>
								<el-option label="校长" value="11"></el-option>
								<el-option label="办公室主任" value="12"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.ruleForm.roleId !='5'">
						<el-form-item label="角色所属机构" prop="orgId" style="white-space: nowrap">
							<el-tree-select
								v-model="state.ruleForm.orgId"
								:data="state.sysOrgData"
								:render-after-expand="false"
								style="width: 500px"
								filterable
								show-all-levels
							/>
						</el-form-item>
					</el-col>
					<el-col class="mb20" v-if="state.ruleForm.roleId == '5'">
						<el-form-item label="学生" prop="studentId">
							<el-select
								v-model="state.ruleForm.studentId"
								filterable
								remote
								reserve-keyword
								placeholder="请输入学生学号进行搜索"
								remote-show-suffix
								:remote-method="remoteMethod"
								:loading="state.loading"
								style="width: 500px"
							>
								<el-option v-for="item in state.options" :key="item.id" :label="item.nickName" :value="item.id" :disabled="item.disabled">
									<span style="float: left">{{ item.username }}</span>
									<span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">{{ item.nickName }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(authorizeAddDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="authorizeAddDialog">
import { reactive, ref } from 'vue';
import { systemApi } from '/@/api/system';
import { userApi } from '/@/api/user';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
const { orgBOETree,orgSchoolOnlyTree,orgSchoolTree } = systemApi();
const { studentListByPage,saveUserRoleRelationship} = userApi();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const rules = reactive<FormRules<any>>({
	roleId: [
		{
			required: true,
			message: '请选择角色',
			trigger: 'change',
		},
	],

	orgId: [
		{
			required: true,
			message: '请选择机构',
			trigger: 'change',
		},
	],
	studentId: [
		{
			required: true,
			message: '请选择学生',
			trigger: 'change',
		},
	],
});

// 定义变量内容
const authorizeAddDialogFormRef = ref();
const state = reactive({
	ruleForm: {
		userId: '',
		roleId: '',
		orgId: '',
		studentId: '',
	},
	sysOrgData: [] as any[], // 部门数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '新增用户角色',
		submitTxt: '新 增',
	},
	loading: false,
	options: [
		{
			id: '1',
			nickName: '',
			username: '请输入学生学号进行搜索',
			disabled: true,
		},
	],
});

// 打开弹窗
const openDialog = (userId: string) => {
	clearForm();
	state.ruleForm.userId = userId;
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};

const roleChange = async () => {
  state.ruleForm.orgId = '';
  switch (state.ruleForm.roleId) {
    case '0': {
      let org = {
        value: '1',
        label: '教育云平台',
      }
      state.sysOrgData = [];
      state.sysOrgData.push(org)
      break;
    }
    case '1': {
      state.sysOrgData = [];
      const res = await orgSchoolTree()
      if (res.status === 200) {
        state.sysOrgData = res.data;
      }
      break;
    }
    case '2':
    case '3':
    case '7': {
      state.sysOrgData = [];
      const res = await orgSchoolOnlyTree()
      if (res.status === 200) {
        state.sysOrgData = res.data;
      }
      break;
    }
    case '6': {
      let org = {
        value: '3',
        label: '昆区教育局',
      }
      state.sysOrgData = [];
      state.sysOrgData.push(org)
      break;
    }
    case '8':
    case '9':
    case '10':
    case '11':
    case '12': {
      state.sysOrgData = [];
      const res = await orgBOETree()
      if (res.status === 200) {
        state.sysOrgData = res.data;
      }
    }
  }
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
      const res = await saveUserRoleRelationship(state.ruleForm)
      if (res.status === 200) {
        ElMessage.success('更改成功');
        emit('refresh');
      }else{
        ElMessage.error('更改失败');
      }
			closeDialog();
		}
	});
};

const remoteMethod = async (query: string) => {
	if (query !== '') {
		state.loading = true;
		const res = await studentListByPage({
			userName: query,
			nickName: '',
		});
		if (res.status === 200) {
			state.options = res.data.records;
			state.loading = false;
		}
	}
};

const clearForm = () => {
	state.ruleForm = {
		userId: '',
		roleId: '',
		orgId: '',
		studentId: '',
	};
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
